﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using SAASDEMO.ViewModel.Ten.TenantVMs;
using SAASDEMO.DataAccess;
using SAASDEMO.Common;
using System.Linq;

namespace SAASDEMO.Controllers
{
    [Area("Ten")]
    [ActionDescription("租户信息")]
    public partial class TenantController : BaseController
    {
        #region Search
        [ActionDescription("Sys.Search")]
        public ActionResult Index()
        {
            var vm = Wtm.CreateVM<TenantListVM>();
            return PartialView(vm);
        }

        [ActionDescription("Sys.Search")]
        [HttpPost]
        public string Search(TenantSearcher searcher)
        {
            var vm = Wtm.CreateVM<TenantListVM>(passInit: true);
            if (ModelState.IsValid)
            {
                vm.Searcher = searcher;
                return vm.GetJson(false);
            }
            else
            {
                return vm.GetError();
            }
        }

        #endregion

        #region Create
        [ActionDescription("Sys.Create")]
        public ActionResult Create()
        {
            var vm = Wtm.CreateVM<TenantVM>();
            //正常这里可以根据规则 生成租户编号和域名 （我懒得写了，直接录入了，根据自己需求自己改）

            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("Sys.Create")]
        public ActionResult Create(TenantVM vm)
        {
            using (var trans = DC.BeginTransaction())
            {
                if (!ModelState.IsValid)
                {
                    return PartialView(vm);
                }
                else
                {
                    vm.DoAdd();
                    if (!ModelState.IsValid)
                    {
                        vm.DoReInit();
                        return PartialView(vm);
                    }
                    else
                    {
                        //我这代码直接写这了 生成租户库和基本信息 随便写了下简单的系统表数据
                        var NDC = new DataContext(Wtm.ConfigInfo.Connections[0].Value.Replace("SAASDEMODB", "SAASDEMODB" + vm.Entity.Code), DBTypeEnum.SqlServer);
                        var Result = NDC.Database.EnsureCreated();

                        if (Result)
                        {
                            var role = DC.Set<FrameworkRole>().Where(x => x.ID == vm.Entity.RoleId).FirstOrDefault();
                            //角色拥有的菜单权限
                            var pr = DC.Set<FunctionPrivilege>().Where(x => x.RoleCode == role.RoleCode).ToList();
                            var user = new FrameworkUser
                            {
                                ITCode = vm.Entity.Account,
                                Password = Utils.GetMD5String("000000"),
                                IsValid = true,
                                Name = vm.Entity.Name,
                                TenantCode = "SAASDEMODB" + vm.Entity.Code
                            };

                            var userrole = new FrameworkUserRole
                            {
                                UserCode = vm.Entity.Account,
                                RoleCode = role.RoleCode
                            };


                            NDC.Set<FrameworkUser>().Add(user);
                            NDC.Set<FrameworkRole>().Add(role);
                            NDC.Set<FrameworkUserRole>().Add(userrole);
                            //这里框架自带角色表  页面权限FunctionPrivilege表没有加父级菜单数据 会导致约束冲突。后期自己添加租户角色表吧
                            NDC.Set<FrameworkMenu>().AddRange(DC.Set<FrameworkMenu>().CheckContain(pr.Select(x => x.MenuItemId).ToList(), x => x.ID).ToList());
                            NDC.Set<FunctionPrivilege>().AddRange(pr);
                            NDC.SaveChanges();

                            //云解析DNS-添加解析记录
                            if (!new CommonHelp().DomainNameResolution(vm.Entity.Code))
                            {
                                trans.Rollback();
                                return FFResult().CloseDialog().RefreshGrid().Alert("域名解析失败！");
                            }
                        }
                        else
                        {
                            trans.Rollback();
                            return FFResult().CloseDialog().RefreshGrid().Alert("租户信息初始化失败！");
                        }
                        trans.Commit();
                        return FFResult().CloseDialog().RefreshGrid();
                    }
                }
            }
        }
        #endregion

        #region Edit
        [ActionDescription("Sys.Edit")]
        public ActionResult Edit(string id)
        {
            var vm = Wtm.CreateVM<TenantVM>(id);
            return PartialView(vm);
        }

        [ActionDescription("Sys.Edit")]
        [HttpPost]
        [ValidateFormItemOnly]
        public ActionResult Edit(TenantVM vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                vm.DoEdit();
                if (!ModelState.IsValid)
                {
                    vm.DoReInit();
                    return PartialView(vm);
                }
                else
                {
                    return FFResult().CloseDialog().RefreshGridRow(vm.Entity.ID);
                }
            }
        }
        #endregion

        #region Delete
        [ActionDescription("Sys.Delete")]
        public ActionResult Delete(string id)
        {
            var vm = Wtm.CreateVM<TenantVM>(id);
            return PartialView(vm);
        }

        [ActionDescription("Sys.Delete")]
        [HttpPost]
        public ActionResult Delete(string id, IFormCollection nouse)
        {
            var vm = Wtm.CreateVM<TenantVM>(id);
            vm.DoDelete();
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid();
            }
        }
        #endregion

        #region Details
        [ActionDescription("Sys.Details")]
        public ActionResult Details(string id)
        {
            var vm = Wtm.CreateVM<TenantVM>(id);
            return PartialView(vm);
        }
        #endregion

        #region BatchEdit
        [HttpPost]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(string[] IDs)
        {
            var vm = Wtm.CreateVM<TenantBatchVM>(Ids: IDs);
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult DoBatchEdit(TenantBatchVM vm, IFormCollection nouse)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return PartialView("BatchEdit", vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert(Localizer["Sys.BatchEditSuccess", vm.Ids.Length]);
            }
        }
        #endregion

        #region BatchDelete
        [HttpPost]
        [ActionDescription("Sys.BatchDelete")]
        public ActionResult BatchDelete(string[] IDs)
        {
            var vm = Wtm.CreateVM<TenantBatchVM>(Ids: IDs);
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("Sys.BatchDelete")]
        public ActionResult DoBatchDelete(TenantBatchVM vm, IFormCollection nouse)
        {
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return PartialView("BatchDelete", vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert(Localizer["Sys.BatchDeleteSuccess", vm.Ids.Length]);
            }
        }
        #endregion

        #region Import
        [ActionDescription("Sys.Import")]
        public ActionResult Import()
        {
            var vm = Wtm.CreateVM<TenantImportVM>();
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("Sys.Import")]
        public ActionResult Import(TenantImportVM vm, IFormCollection nouse)
        {
            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return PartialView(vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert(Localizer["Sys.ImportSuccess", vm.EntityList.Count.ToString()]);
            }
        }
        #endregion

        [ActionDescription("Sys.Export")]
        [HttpPost]
        public IActionResult ExportExcel(TenantListVM vm)
        {
            return vm.GetExportData();
        }

    }
}
